import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qgchat/common/action/compress_photo/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/api.dart';
import 'package:qgchat/http/io.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:qgchat/widgets/appbarCustom.dart';

/*
 * 基本资料页面
 * page基本资料
 */

class BasicInfo extends StatefulWidget {
  @override
  _BasicInfoState createState() => _BasicInfoState();
}

class _BasicInfoState extends State<BasicInfo> {
  UserInfoModel userInfo; // 用户信息实体

  String userImg; // 用户头像
  String userName; // 用户名字
  File imgFile; // 本地头像地址
  bool first = true;

  bool isLoding = false; // 是否正在上传图片

  String qlyToken; // 七牛云token

  TextEditingController iptUserNameController = TextEditingController();

// methods----------------------------------------------------------------------

  // 保存按钮
  void _saveClick() {
    if ("$userName".length > 10) {
      showToast("昵称最长10个字符喔");
      return;
    }
    UserApis.setName(userName).then((res) {
      showToast('修改成功');
      UserState user = state(context, 'user');
      user.userInfo();
      Navigator.of(context).pop();
    });
  }

  // 头像被点击
  void _avatarClick() {
    showBottomSheet();
  }

  // add被点击
  void _addClick() {
    showBottomSheet();
  }

  // 显示底部面板
  showBottomSheet() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          title: Text("选择图片"),
          message: Text("选择以下选项获取图片"),
          cancelButton: CupertinoActionSheetAction(
            onPressed: () => Navigator.pop(context),
            child: Text("取消"),
          ),
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () async {
                var image = await ImagePicker.pickImage(source: ImageSource.camera);
               if(image == null) return;
                setState(() {
                  isLoding = true;
                });
                CompressPhoto.compressPhoto(image, (file) {
                  onUpload(file);
                });
                Navigator.pop(context);
              },
              child: Text("相机"),
            ),
            CupertinoActionSheetAction(
              onPressed: () async {
                var image = await ImagePicker.pickImage(source: ImageSource.gallery);
                if(image == null) return;
                setState(() {
                  isLoding = true;
                });
                CompressPhoto.compressPhoto(image, (file) {
                  onUpload(file);
                });
                Navigator.pop(context);
              },
              child: Text("系统相册"),
            ),
          ],
        );
      },
    );
  }

  // 上传头像
  void onUpload(File img) async {
    Io.updateFile('vedio/upload', img, size: '51200000').then((res) {
      if (res.data['status'] == 1) {
        Io.post('Mysetting/editavatar', data: {
          'member_head': res.data['data'],
        }).then((res) {
          if (res['status'] == 1) {
            state(context, 'user').userInfo();
            showToast('上传成功');
          } else {
            showToast(res.data['msg']);
          }
        });
      } else {
        showToast(res.data['msg']);
      }
      setState(() {
        isLoding = false;
      });
    });
  }

// widget-----------------------------------------------------------------------

  /// appbar
  Widget appbar() {
    return AppbarCustom(
      '基本资料',
      rightText: '保存',
      rightOnPressed: _saveClick,
    );
  }

  /// 头像
  Widget avatar() {
    /// 头像显示
    Widget getHead() {
      if (isLoding) {
        return Container(
          color: Colors.white,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CupertinoActivityIndicator(),
              Container(
                margin: EdgeInsets.only(top: px(10)),
                child: Text("上传中..."),
              ),
            ],
          ),
        );
      } else if (userImg == '' || userImg == null) {
        // 本地
        return Image.asset(
          'assets/images/icon/unloggedUser.png',
          fit: BoxFit.cover,
        );
      } else {
        return CachedNetworkImage(
          imageUrl: "$userImg",
          fit: BoxFit.cover,
          errorWidget: (context, url, error) {
            return Config.errorNetImage;
          },
        );
      }
    }

    return Container(
      width: w100(context),
      height: px(180),
      margin: EdgeInsets.only(top: px(30)),
      alignment: Alignment.center,
      child: Container(
        width: px(180),
        child: Stack(
          overflow: Overflow.visible,
          children: <Widget>[
            /// 头像背景图
            Positioned(
              child: GestureDetector(
                onTap: _avatarClick,
                child: Container(
                  width: px(180),
                  height: px(180),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(px(90)),
                    child: getHead(),
                  ),
                ),
              ),
            ),

            /// add按钮
            Positioned(
              bottom: px(0),
              right: px(-20),
              child: GestureDetector(
                onTap: _addClick,
                child: Container(
                  width: px(60),
                  height: px(60),
                  child: Image.asset('assets/images/icon/myAvatarAdd.png'),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 姓名&性别
  Widget nameAndSex() {
    return Container(
        height: px(120),
        padding: EdgeInsets.symmetric(horizontal: px(30)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            /// 姓名
            Container(
                width: px(400),
                margin: EdgeInsets.only(left: px(8)),
                child: TextField(
                  onChanged: (val) {
                    userName = val;
                  },
                  controller: iptUserNameController,
                  textAlign: TextAlign.center,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                  ),
                  style: TextStyle(
                    fontSize: px(38),
                    color: col('303133'),
                  ),
                ),),
          ],
        ),);
  }

  @override
  Widget build(BuildContext context) {
    return stateBuilder(context, 'user', (user) {
      userInfo = user.info;
      if (userInfo != null) {
        userImg = userInfo.memberHead.trim();
        if (first) {
          userName = userInfo.memberNickname;
          iptUserNameController.text = userName;
          first = false;
        }
        iptUserNameController.text = userName;
        iptUserNameController.selection =
            TextSelection.collapsed(offset: userName.length);
      }

      return Scaffold(
        appBar: appbar(),
        body: Container(
          child: Column(
            children: <Widget>[
              avatar(),
              nameAndSex(),
            ],
          ),
        ),
      );
    });
  }
}
